<template>
	<xn-form-container
		:title="formData.id ? '编辑商品' : '增加商品'"
		:width="700"
		:visible="visible"
		:destroy-on-close="true"
		@close="onClose"
	>
		<a-form ref="formRef" :model="formData" :rules="formRules" layout="horizontal">
			<a-form-item label="商品盒子：" name="goodsBoxId">
				<a-select
					v-model:value="formData.goodsBoxId"
					:options="boxOptions"
					style="width: 100%"
					placeholder="请选择商品盒子"
				/>
			</a-form-item>
			<a-form-item label="商品名称：" name="goodsName">
				<a-input v-model:value="formData.goodsName" placeholder="请输入商品名称" allow-clear />
			</a-form-item>
			<a-form-item label="商品介绍：" name="sellingPoint">
				<a-textarea :rows="8" v-model:value="formData.sellingPoint" placeholder="请输入商品介绍" allow-clear />
			</a-form-item>
			<a-form-item v-if="formData.imgUrlList" label="更换图片（会清空原来的图片）：" name="isChangeImgs">
				<a-radio v-model:checked="formData.isChangeImgs">更换图片</a-radio>
			</a-form-item>
			<a-form-item label="商品图片：">
				<div class="clearfix">
					<a-upload
						v-model:file-list="fileList"
						:beforeUpload="beforeUpload"
						list-type="picture-card"
						@preview="handlePreview"
						action="http://localhost:9003/api/webapp/dev/file/uploadMinioReturnUrl"
					>
						<div v-if="fileList.length < 7">
							<plus-outlined />
							<div style="margin-top: 8px">Upload</div>
						</div>
					</a-upload>
					<a-modal :open="previewVisible" :title="previewTitle" :footer="null" @cancel="handleCancel">
						<img alt="example" style="height:800px;width: 100%" :src="previewImage" />
					</a-modal>
				</div>
			</a-form-item>
			<!--            <a-form-item label="商品视频：" name="goodsVideo">-->
			<!--                <a-input v-model:value="formData.goodsVideo" placeholder="请输入商品视频" allow-clear />-->
			<!--            </a-form-item>-->
			<a-form-item label="商品详情：" name="goodsDetails">
				<a-textarea :rows="8" v-model:value="formData.goodsDetails" placeholder="请输入商品详情" allow-clear />
			</a-form-item>
			<a-form-item label="售价，整数：" name="goodsPriceFee">
				<a-input-number v-model:value="formData.goodsPriceFee" placeholder="请输入售价，整数" :min="1"
								:max="10000" style="width: 100%" />
			</a-form-item>
			<a-form-item label="市场价，整数：" name="goodsMarketPriceFee">
				<a-input-number v-model:value="formData.goodsMarketPriceFee" placeholder="请输入市场价，整数" :min="1"
								:max="10000" style="width: 100%" />
			</a-form-item>
			<a-form-item label="排序：" name="goodsSort">
				<a-input-number v-model:value="formData.goodsSort" placeholder="请输入排序" :min="1" :max="10000"
								style="width: 100%" />
			</a-form-item>
			<a-form-item label="实际库存：" name="actualStockCount">
				<a-input-number v-model:value="formData.actualStockCount" placeholder="请输入实际库存" :min="1"
								:max="10000" style="width: 100%" />
			</a-form-item>
			<a-form-item label="商品状态：" name="goodsStatus">
				<a-select v-model:value="formData.goodsStatus" placeholder="请选择商品状态："
						  :options="goodsStatusOptions" />
			</a-form-item>
			<a-form-item label="可售卖库存：" name="availableStockCount">
				<a-input-number v-model:value="formData.availableStockCount" placeholder="请输入可售卖库存" :min="1"
								:max="10000" style="width: 100%" />
			</a-form-item>
			<a-form-item label="标签选择：" name="tagList">
				<a-select
					v-model:value="formData.tagList"
					mode="tags"
					style="width: 100%"
					:options="options"
					@change="handleChange"
				></a-select>
			</a-form-item>
			<div v-if="isShowAttrEdit" >
				<a-form-item>
					<a-button type="primary" @click="formAttributeINTRODUCTIONRef.onOpen(formData)"
							  v-if="hasPerm('bizGoodsAdd')">
						<template #icon>
							<plus-outlined />
						</template>
						配置介绍属性
					</a-button>
				</a-form-item>
				<a-form-item>
					<a-button type="primary" @click="formAttributeSTANDARDSRef.onOpen(formData)"
							  v-if="hasPerm('bizGoodsAdd')">
						<template #icon>
							<plus-outlined />
						</template>
						配置规格属性
					</a-button>
				</a-form-item>
			</div>

		</a-form>
		<template #footer>
			<a-button style="margin-right: 8px" @click="onClose">关闭</a-button>
			<a-button type="primary" @click="onSubmit" :loading="submitLoading">保存</a-button>
		</template>

			<form-i-n-t-r-o-d-u-c-t-i-o-n-attribute ref="formAttributeINTRODUCTIONRef">

			</form-i-n-t-r-o-d-u-c-t-i-o-n-attribute>
			<form-s-t-a-n-d-a-r-d-s-attribute  ref="formAttributeSTANDARDSRef">

			</form-s-t-a-n-d-a-r-d-s-attribute>

	</xn-form-container>
</template>

<script setup name="bizGoodsForm">
// 属性配置1
import FormINTRODUCTIONAttribute from "@/views/biz/lancerGoods/formINTRODUCTIONAttribute.vue";

const formAttributeINTRODUCTIONRef = ref(false);
const formAttributeSTANDARDSRef = ref(false);

import tool from "@/utils/tool";
import { cloneDeep } from "lodash-es";
import { required } from "@/utils/formRules";
import bizGoodsApi from "@/api/biz/bizGoodsApi";
import { message } from "ant-design-vue";
import bizGoodsBoxApi from "@/api/biz/bizGoodsBoxApi";
import FormAttribute from "@/views/biz/lancerGoods/formINTRODUCTIONAttribute.vue";
import FormSTANDARDSAttribute from "@/views/biz/lancerGoods/formSTANDARDSAttribute.vue";
import BizGoodsTagApi from "@/api/biz/bizGoodsTagApi";
// 抽屉状态
const visible = ref(false);
const emit = defineEmits({ successful: null });
const formRef = ref();
// 表单数据
const formData = ref({});
const submitLoading = ref(false);
const goodsStatusOptions = ref([]);
const isShowAttrEdit=ref(false)
// 打开抽屉
const onOpen = (record) => {
	// 加载默认的标签
	BizGoodsTagApi.allTag().then(x => {
		options.value = x;
	});
	visible.value = true;
	if (record) {


		isShowAttrEdit.value=true
		const param = {
			id: record.id
		};
		bizGoodsApi.bizGoodsDetail(param).then(x => {
			// 照片初始化
			let fileListOld=[]
			let imgUrlList = x.imgUrlList;
			if (imgUrlList!=null){
				for (let i = 0; i < imgUrlList.length; i++) {
					fileListOld.push({
						uid: i,
						name: i,
						status: 'done',
						url:imgUrlList[i]}
					)
				}
				fileList.value=fileListOld
			}

			formData.value = x;
		});
	}
	else {
		isShowAttrEdit.value=false
	}
	goodsStatusOptions.value = tool.dictList("GOODS_STATUS");
};
// 关闭抽屉
const onClose = () => {
	formRef.value.resetFields();
	formData.value = {};
	visible.value = false;
	fileList.value=[]
};
// 默认要校验的
const formRules = {
	goodsName: [required("请输入商品名称")],
	sellingPoint: [required("请输入商品介绍")],
	goodsDetails: [required("请输入商品详情")],
	goodsPriceFee: [required("请输入售价")],
	goodsMarketPriceFee: [required("请输入市场价")],
	goodsSort: [required("请选择排序")],
	actualStockCount: [required("请输入实际库存")],
	goodsStatus: [required("请选择商品状态")],
	availableStockCount: [required("请输入可售卖库存")],
	tagList: [required("请输入商品标签")]
};
// 验证并提交数据
const onSubmit = () => {
	formRef.value.validate().then(() => {
		submitLoading.value = true;
		const formDataParam = cloneDeep(formData.value);
		let id = formDataParam.id;
		const res = new FormData();
		res.append("goodsName", formDataParam.goodsName);
		res.append("sellingPoint", formDataParam.sellingPoint);
		res.append("goodsDetails", formDataParam.goodsDetails);
		res.append("goodsMarketPriceFee",formDataParam.goodsMarketPriceFee);
		res.append("goodsPriceFee", formDataParam.goodsPriceFee);
		res.append("actualStockCount", formDataParam.actualStockCount);
		res.append("goodsSort", formDataParam.goodsSort);
		res.append("goodsBoxId", formDataParam.goodsBoxId);
		res.append("id", id);
		res.append("goodsStatus", formDataParam.goodsStatus);
		res.append("availableStockCount", formDataParam.availableStockCount);
		res.append("tagList", formDataParam.tagList);
		// 新增
		if (id==null){
			fileList.value.forEach(x => {
				res.append("goodsImgUrls", x.originFileObj);
			});
			// 提示用户
			message.success("创建商品后，请再编辑界面，配置商品的属性信息")
		}
		// 更新
		else {
			res.append("isChangeImgs", formData.value.isChangeImgs?"YES":"NO")
			if (formData.value.isChangeImgs){
				fileList.value.forEach(x => {
					res.append("goodsImgUrls", x.originFileObj);
				});
			}
		}
		bizGoodsApi
			.bizGoodsSubmitForm(res, id)
			.then(() => {
				onClose();
				emit("successful");
			})
			.finally(() => {
				submitLoading.value = false;
			});
	});
};
// 抛出函数
defineExpose({
	onOpen
});

const beforeUpload = (file) => {
	const isPNG = (file.type === "image/png" || file.type === "image/jpeg");
	if (!isPNG) {
		message.error(`${file.name}暂且只支持png和jpg图片格式`);
		return false;
	}
	fileList.value = [...(fileList.value || []), file];
	return false;
};
const handleRemove = file => {
	const index = fileList.value.indexOf(file);
	const newFileList = fileList.value.slice();
	newFileList.splice(index, 1);
	fileList.value = newFileList;
};


const previewVisible = ref(false);
const previewImage = ref("");
const previewTitle = ref("");
// 文件上传
const fileList = ref([]);
const handleCancel = () => {
	previewVisible.value = false;
	previewTitle.value = "";
};

function getBase64(file) {
	return new Promise((resolve, reject) => {
		const reader = new FileReader();
		reader.readAsDataURL(file);
		reader.onload = () => resolve(reader.result);
		reader.onerror = error => reject(error);
	});
}

const handlePreview = async file => {
	if (!file.url && !file.preview) {
		file.preview = await getBase64(file.originFileObj);
	}
	previewImage.value = file.url || file.preview;
	previewVisible.value = true;
	previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1);
};
// 商品盒子
const boxOptions = ref([]);
// 请求API
bizGoodsBoxApi.allGoodsBox().then(x => {
	boxOptions.value = x;
});

const handleChange = (value) => {
	console.log(`selected ${value}`);
};
const value = ref([]);
const options = ref([]);

</script>
